const express = require('express');
const admin = express.Router();
const jwt = require('jsonwebtoken')
const bcrypt = require('bcrypt')
const { User, validateUser } = require('../model/user')


// 登陆功能
admin.post('/login',
    function (req, res, next) {
        if (!req.body.username) {
            return res.sendResult(null, 400, "用户名不能为空");
        }
        if (!req.body.password) {
            return res.sendResult(null, 400, "密码不能为空");
        }
        next()
    },
    async function (req, res) {
        const { username, password } = req.body
        let content = { name: username }; // 要生成token的主题信息
        let secretOrPrivateKey = "curry";// 这是加密的key（密钥）
        let token = jwt.sign(content, secretOrPrivateKey, {
            expiresIn: 60 * 60 * 1  // 1小时过期
        });
        let user = await User.findOne({ username })
        if (user) {
            let isValid = await bcrypt.compare(password, user.password)
            if (isValid) {
                user.token = token
                return res.sendResult(user, 200, "登录成功")
            } else {
                return res.sendResult(null, 400, "密码错误");
            }
        } else {
            return res.sendResult(null, 400, "无该用户");
        }

    }
);
// 管理员列表
// admin.get('/user', async (req, res) => {
//     let query = req.query.query
//     let pagesize = parseInt(req.query.pagesize)
//     let pagenum = parseInt(req.query.pagenum)
//     let count = await User.countDocuments({});
//     // 页码对应的数据查询开始位置
//     let start = (pagenum - 1) * pagesize;
//     // 将用户信息从数据库中查询出来
//     let users = await User.find({}).limit(pagesize).skip(start)
//     // 渲染用户列表模块
//     let data = {}
//     data.users = users
//     data.total = count;
//     return res.sendResult(data, 200, "获取成功")
// })
admin.get('/user', async (req, res) => {
    let query = req.query.query
    let pagesize = parseInt(req.query.pagesize)
    let pagenum = parseInt(req.query.pagenum)
    let start = (pagenum - 1) * pagesize;
    let reg = new RegExp('.*' + query + '.*$')
    let users = await User.find({ "username": { $regex: reg, $options: 'i' } }).limit(pagesize).skip(start);
    // let users = await User.find({})
    if (!users) {
        return res.sendResult(null, 400, "没有搜索到用户");
    } else {
        let count = await User.find({ "username": { $regex: reg, $options: 'i' } }).countDocuments();
        let data = {};
        data.users = users;
        data.total = count;
        return res.sendResult(data, 200, "获取成功");
    }
})
//添加用户
admin.post("/user",
    // 验证参数
    function (req, res, next) {
        if (!req.body.username) {
            return res.sendResult(null, 400, "用户名不能为空");
        }
        if (!req.body.password) {
            return res.sendResult(null, 400, "密码不能为空");
        }
        if (!req.body.email) {
            return res.sendResult(null, 400, "邮箱不能为空");
        }
        if (!req.body.role) {
            return res.sendResult(null, 400, "角色不能为空");
        }
        next();
    },
    // 处理业务逻辑
    async function (req, res, next) {
        let user = await User.findOne({ email: req.body.email });
        if (user) {
            return res.sendResult(null, 400, "邮箱已存在");
        } else {
            let salt = await bcrypt.genSalt(10);
            let password = await bcrypt.hash(req.body.password, salt);
            req.body.password = password;
            await User.create(req.body)
            res.sendResult(null, 201, "创建成功");
        }

    }
);
// 获取用户信息
admin.get("/user/:id",
    // 参数验证
    function (req, res, next) {
        if (!req.params.id) {
            return res.sendResult(null, 400, "用户ID不能为空");
        }
        if (isNaN(parseInt(req.params.id))) return res.sendResult(null, 400, "用户ID必须是数字");
        next();
    },
    async function (req, res, next) {
        let id = req.params.id;
        let user = await User.findOne({ _id: id });
        res.sendResult(user, 200, "查询成功");
    }
);
//更新用户
admin.put("/user/:id", async (req, res) => {
    let id = req.params.id;
    // 根据id修改用户信息
    let { email, role } = req.body;
    await User.updateOne({ _id: id }, {
        email: email,
        role: role,
    });
    res.sendResult(null, 200, "更新成功");
})
//删除用户
admin.delete("/user/:id", async (req, res) => {
    await User.findOneAndDelete({ _id: req.params.id });
    res.sendResult(null, 200, "删除成功");
})

module.exports = admin;